using System;
using System.Collections;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace SecuBat.Notification
{
	/// <summary>
	/// Summary description for TaskPackage.
	/// </summary>
	[Serializable, XmlInclude(typeof(NotificationItem))]
	public class NotificationPackage
	{
		private ArrayList _tasks;

		public ArrayList Tasks
		{
			get { return _tasks; }
			set { _tasks = value; }
		}

		public NotificationPackage()
		{
			_tasks = new ArrayList();
		}

		public NotificationPackage(ArrayList list)
		{
			_tasks = list;
		}

		public static NotificationPackage FromFile(String fileName)
		{
			NotificationPackage container = null;
			StreamReader reader = null;
			try
			{
				reader = new StreamReader(fileName);
				try
				{
					XmlSerializer serializer = new XmlSerializer(typeof(NotificationPackage));
					container = (NotificationPackage) serializer.Deserialize(reader);
				}
				catch (Exception e)
				{
					throw new FileLoadException("Error while deserializing XML package from file '" + fileName + "'!", e);
				}
			}
			catch (FileLoadException e)
			{
				throw e;
			}
			catch (Exception e)
			{
				throw new FileLoadException("Could not open file '" + fileName + "' for reading!", e);
			}
			finally
			{
				reader.Close();
			}
			return container;
		}


		public void SaveToFile(String fileName)
		{
			TextWriter writer = null;
			try
			{
				writer = new StreamWriter(fileName, false);
				try
				{
					XmlSerializer serializer = new XmlSerializer(this.GetType());
					serializer.Serialize(writer, this);
				}
				catch (Exception e)
				{
					writer.Close();
					File.Delete(fileName);
					throw new FileLoadException("Error while serializing XML package to file '" + fileName + "'!", e);
				}
			}
			catch (FileLoadException e)
			{
				throw e;
			}
			catch (Exception e)
			{
				throw new FileLoadException("Could not open file '" + fileName + "' for writing!", e);
			}
			finally
			{
				if ( writer != null)
					writer.Close();
			}
		}
	}
}
